import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { getPlaylistDetailAPI, getPlaylistTrackAllAPI } from "../api";
import { RootState } from "@/store";

interface IDetailArg {
  id: number,
  limit?: number,
  offset?: number
}

export const feachMenuDetailAction = createAsyncThunk<void, IDetailArg, { state: RootState }>("menudetail", async (arg: IDetailArg, { dispatch, getState }) => {
  const { id, limit = 50, offset = 0 } = arg
  const { playlist } = await getPlaylistDetailAPI(id)
  dispatch(changeMenuDetilAction(playlist))

  const state = getState()
  const menuTranks = state.playlist.menuTranks

  const AddTranks: any[] = []
  // 进行逻辑判断 是否要加入我们的歌单列表中
  const { songs } = await getPlaylistTrackAllAPI(id, limit, offset)
  if (menuTranks.length >= playlist.trackIds.length) return
  songs.forEach((item: any) => {
    const finalIndex = menuTranks.findIndex(menu => menu.id === item.id)
    if (finalIndex === -1) {
      AddTranks.push(item)
    }
  })
  dispatch(changeMenuTranksAction(AddTranks))
})


interface IState {
  menuDetail: any,
  menuTranks: any[]
}

const initialState: IState = {
  menuDetail: {},
  menuTranks: []
}

const playlistSlice = createSlice({
  name: "playlist",
  initialState,
  reducers: {
    changeMenuDetilAction(state, { payload }) {
      state.menuDetail = payload
    },
    changeMenuTranksAction(state, { payload }) {
      state.menuTranks = [...state.menuTranks, ...payload]
    }
  }
})

export const { changeMenuDetilAction, changeMenuTranksAction } = playlistSlice.actions
export default playlistSlice.reducer